package com.fs.filter;

import com.fs.decorator.RewriteResponseDecorator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Slf4j
public class SystemMonitorFilter implements Ordered, GatewayFilter {
    private String regex;

    public SystemMonitorFilter(String regex) {
        this.regex = regex;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取路由路径
        String rawPath = exchange.getRequest().getURI().getRawPath();
        //获取需要转发的路径
        String newPath = rawPath.replaceAll(regex, "/${segment}");
        //构建reques请求.添加一个请求头,删除旧的请求头Accpet，只接受json数据
        HttpHeaders.writableHttpHeaders(exchange.getRequest().getHeaders()).remove(HttpHeaders.ACCEPT);
        ServerHttpRequest request = exchange.getRequest().mutate().path(newPath).header("Accept", "application/json").build();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        // 使用新exchange获取响应体
        RewriteResponseDecorator rewriteResponseDecorator = new RewriteResponseDecorator(response);
        //放行
        return chain.filter(exchange.mutate().request(request).response(rewriteResponseDecorator).build());
    }

    @Override
    public int getOrder() {
        //过滤器的优先级
        return -100;
    }



}
